//
//  WPMineLoginVC.m
//  wobingwoyi
//
//  Created by WGP on 16/7/29.
//  Copyright © 2016年 WGP. All rights reserved.
//

#import "WPMineLoginVC.h"
#import "WPRegisterAndForgetView.h"
#import "WPRegisterViewController.h"
#import "WPForgotPasswordVC.h"
#import "NSString+Hash.h"
#import "NSString+WPSizeOfString.h"

@interface WPMineLoginVC ()<UITextFieldDelegate,NSURLSessionDelegate,NSURLSessionDataDelegate>

@property(nonatomic,strong)UITextField *accountTextField;
@property(nonatomic,strong)UITextField *passwordTextField;
@property(nonatomic,strong)WPBtnNoHighLight *weixinBtn;
@property(nonatomic,strong)WPBtnNoHighLight *weiboBtn;
@property(nonatomic,strong)WPBtnNoHighLight *qqBtn;

@end

@implementation WPMineLoginVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.hidden = YES;
    [self setupUI];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(void)viewDidDisappear:(BOOL)animated
{
    [super viewDidDisappear:animated];
    [self dismiss];
}

-(void)setupUI
{
    UIImageView *headerImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LoginHeader"]];
    [self.view addSubview:headerImageView];
    
    UIImageView *iconView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"huiqu"]];
    [iconView sizeToFit];
    [headerImageView addSubview:iconView];
    
    UIButton *cancelBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [cancelBtn setBackgroundImage:[UIImage imageNamed:@"cancel"] forState:UIControlStateNormal];
    [cancelBtn addTarget:self action:@selector(cancelBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:cancelBtn];
    
    UITextField *accountTextField = [[UITextField alloc] init];
    accountTextField.placeholder = @"请输入手机号";
    
//    自动填充账号
    WPUserAccount *account = [WPUserAccountViewModel sharedInstance].userAccount;
    WPUser *user = account.user;
    if (user.account.length)
    {
        accountTextField.text = user.account;
    }
    
    accountTextField.keyboardType = UIKeyboardTypeNumberPad;
    accountTextField.font = [UIFont systemFontOfSize:16];
    self.accountTextField = accountTextField;
    [self.view addSubview:accountTextField];
    
    UIView *firstLineView = [[UIView alloc] init];
    firstLineView.backgroundColor = GLobalLineColor;
    [self.view addSubview:firstLineView];
    
    UITextField *passwordTextField = [[UITextField alloc] init];
    passwordTextField.placeholder = @"请输入登录密码";
    passwordTextField.font = [UIFont systemFontOfSize:16];
    passwordTextField.secureTextEntry = YES;
    self.passwordTextField = passwordTextField;
    self.passwordTextField.delegate = self;
    self.passwordTextField.returnKeyType = UIReturnKeyDone;
    [self.view addSubview:passwordTextField];
    
    UIView *secondLineView = [[UIView alloc] init];
    secondLineView.backgroundColor = GLobalLineColor;
    [self.view addSubview:secondLineView];
    
    UIButton *secureBtn = [WPBtnNoHighLight buttonWithType:UIButtonTypeCustom];
    [secureBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-biyan"] forState:UIControlStateNormal];
    [secureBtn setBackgroundImage:[UIImage imageNamed:@"iconfont-yanjing"] forState:UIControlStateSelected];
    [secureBtn addTarget:self action:@selector(secureBtnDidClick:) forControlEvents:UIControlEventTouchDown];
//    self.passwordTextField = passwordTextField;
    [self.view addSubview:secureBtn];
    
    UIButton *loginBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [loginBtn setBackgroundImage:[UIImage imageNamed:@"normal"] forState:UIControlStateNormal];
     [loginBtn setBackgroundImage:[UIImage imageNamed:@"highLight"] forState:UIControlStateHighlighted];
    [loginBtn setTitle:@"登录" forState:UIControlStateNormal];
    loginBtn.titleLabel.font = [UIFont systemFontOfSize:15*SCALE];
    [loginBtn addTarget:self action:@selector(loginBtnDidClick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:loginBtn];
    
    WPRegisterAndForgetView *registerAndForgetView = [WPRegisterAndForgetView registerAndForgetPwdViewWith:^(WPLoginViewType type) {
        
        [self.view endEditing:YES];
        
        if (type == WPLoginViewTypeRegister)
        {
            [self.navigationController pushViewController:[WPRegisterViewController new] animated:YES];
        }
        else if(type == WPLoginViewTypeForgetPwd)
        {
            [self.navigationController pushViewController:[WPForgotPasswordVC new] animated:YES];
        }
        
    }];
    [self.view addSubview:registerAndForgetView];
    
    [headerImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self.view);
        make.height.mas_equalTo(200*SCALE_FULL);
    }];
    
    [cancelBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(35);
        make.left.equalTo(self.view).offset(15);
        
    }];
    
    [accountTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(headerImageView.mas_bottom).offset(44*SCALE_FULL);
        make.left.equalTo(self.view).offset(15*KWIDTH_SCALE);
        make.right.equalTo(self.view).offset(-15*KWIDTH_SCALE);
    }];
    
    [firstLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.equalTo(self.view).offset(15*KWIDTH_SCALE);
        make.right.equalTo(self.view).offset(-15*KWIDTH_SCALE);
        make.top.equalTo(accountTextField.mas_bottom).offset(12*SCALE_FULL);
    }];
    
    [passwordTextField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(firstLineView.mas_bottom).offset(12*SCALE_FULL);
        make.left.equalTo(self.view).offset(15*KWIDTH_SCALE);
        make.right.equalTo(self.view).offset(-15*KWIDTH_SCALE);
    }];
    
    [secondLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(0.5);
        make.left.equalTo(self.view).offset(15*KWIDTH_SCALE);
        make.right.equalTo(self.view).offset(-15*KWIDTH_SCALE);
        make.top.equalTo(passwordTextField.mas_bottom).offset(12*SCALE_FULL);
    }];
    
    [secureBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerY.equalTo(passwordTextField);
        make.right.equalTo(self.view).offset(-15*KWIDTH_SCALE);
    }];
    
    [loginBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(secondLineView.mas_bottom).offset(44*SCALE_FULL);
        make.left.equalTo(self.view).offset(20);
        make.right.equalTo(self.view).offset(-20);
    }];
    
    [registerAndForgetView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(loginBtn.mas_bottom).offset(10*SCALE_FULL);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(30);
    }];
    
    [iconView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(headerImageView);
        make.width.height.mas_equalTo(75*KWIDTH_SCALE);
    }];
    
    [self setupOtherLoginBtn];
}

-(void)cancelBtnDidClick
{
    [self.view endEditing:YES];
    [self dismissViewControllerAnimated:YES completion:nil];
}


-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

-(void)secureBtnDidClick:(UIButton *)secureBtn
{
    secureBtn.selected = !secureBtn.selected;
    self.passwordTextField.secureTextEntry = !self.passwordTextField.secureTextEntry;
}

-(void)loginBtnDidClick
{
    if (![NSString isMobile:self.accountTextField.text]) {
        
        [self showErrorInfoWithStatus:@"手机号码格式不正确"];
        return ;
    }
    
    if (!self.passwordTextField.text.length)
    {
        [self showErrorInfoWithStatus:@"请输入密码"];
        return ;
    }
    
    NSString *account = self.accountTextField.text;
    NSString *password = [self.passwordTextField.text md5String];
   
    [self showWithStatus:@"正在登录"];
    
    NSDictionary *dict = @{@"account":account,@"password":password};
    [[WPUserAccountViewModel sharedInstance] globalLoginWith:dict successHandle:^{
        
        //        登录成功
        [self showSuccessInfoWithStatus:@"登陆成功"];
        
        [self.delegate loadUserInfomation:self];
        [self.view endEditing:YES];
        [self.navigationController dismissViewControllerAnimated:YES completion:nil];
       
//        账号过期的时候登陆成功的跳转操作
        if(self.successLoginBlock)
        {
            self.successLoginBlock();
        }
    }];
}

-(void)setupOtherLoginBtn
{
    self.weixinBtn = [WPBtnNoHighLight buttonWithType:UIButtonTypeCustom];
    self.weiboBtn = [WPBtnNoHighLight buttonWithType:UIButtonTypeCustom];
    self.qqBtn = [WPBtnNoHighLight buttonWithType:UIButtonTypeCustom];
    
    [self.weixinBtn setBackgroundImage:[UIImage imageNamed:@"weixin_normal"] forState:UIControlStateNormal];
    [self.weixinBtn setBackgroundImage:[UIImage imageNamed:@"weixin_highlight"] forState:UIControlStateHighlighted];
     [self.weiboBtn setBackgroundImage:[UIImage imageNamed:@"weibo_normal"] forState:UIControlStateNormal];
    [self.weiboBtn setBackgroundImage:[UIImage imageNamed:@"weibo_highlight"] forState:UIControlStateHighlighted];
     [self.qqBtn setBackgroundImage:[UIImage imageNamed:@"qq_normal"] forState:UIControlStateNormal];
    [self.qqBtn setBackgroundImage:[UIImage imageNamed:@"qq_highlight"] forState:UIControlStateHighlighted];
    
    [self.view addSubview:self.weixinBtn];
    [self.view addSubview:self.weiboBtn];
    [self.view addSubview:self.qqBtn];
    
    [self.weixinBtn addTarget:self action:@selector(otherLoginBtnDidClick:) forControlEvents:UIControlEventTouchDown];
     [self.weiboBtn addTarget:self action:@selector(otherLoginBtnDidClick:) forControlEvents:UIControlEventTouchDown];
     [self.qqBtn addTarget:self action:@selector(otherLoginBtnDidClick:) forControlEvents:UIControlEventTouchDown];
    
    
    [self.weixinBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.view).offset(60*KWIDTH_SCALE);
        make.bottom.equalTo(self.view).offset(-25*SCALE_FULL);
    }];
    
    [self.weiboBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.weixinBtn);
    }];
    
    [self.qqBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.view).offset(-60*KWIDTH_SCALE);
        make.bottom.equalTo(self.weixinBtn);
    }];
    
}

-(void)otherLoginBtnDidClick:(WPBtnNoHighLight *)btn
{
    NSString *url = @"user/thirdPartyLogin.do";
    
    //获取设备唯一标示
    NSString *uniqueStr = [self getsTheUniqueIdentifierForTheDevice];
//    NSLog(@"唯一标示:%@",uniqueStr);
    
    if (btn == self.weixinBtn)
    {
        [ShareSDK getUserInfo:SSDKPlatformTypeWechat
               onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
         {
             if (state == SSDKResponseStateSuccess)
             {
                 
//                 NSLog(@"用户标识:uid=%@",user.uid);
//                 NSLog(@"授权凭证: %@",user.credential);
//                 NSLog(@"token=%@",user.credential.token);
//                 NSLog(@"nickname=%@",user.nickname);
//                 NSLog(@"icon = %@",user.icon);
                 
                 [self showWithStatus:@"正在登录"];
                 
                 NSDictionary *dict = @{@"type":@(1),@"name":user.nickname,@"image":user.icon,@"openId":user.rawData[@"unionid"],@"accessToken":user.credential.token,@"equipmentId":uniqueStr};
                 [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                     
                 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     
                     [self dismiss];
                     if ([responseObject[@"result"] isEqualToString:@"success"])
                     {
                         //            保存用户信息
                         WPUserAccount *userAccount = [WPUserAccount yy_modelWithDictionary:responseObject[@"detail"]];
                         [userAccount saveUserAccount];
                         
                         //设置请求头
                         NSString *tokenStr = [userAccount.token yy_modelToJSONString];
                         [[WPNetWorkManager sharedNetWorkManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
                         
                         //用于绑定Alias的  使用NSString 即可
                         [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",userAccount.user.id] callbackSelector:nil object:self];
                         
                         //        登录成功
                         [self showSuccessInfoWithStatus:@"登陆成功"];
                         [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                         
                         //友盟微信账号统计
                         [MobClick profileSignInWithPUID:userAccount.user.account provider:@"Wechat"];
                     }
                     else
                     {
                         [self showErrorInfoWithStatus:responseObject[@"detail"]];
                     }
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     [self dismiss];
                     [self showErrorInfoWithStatus:@"网络错误"];
                 }];
                 
             }
             
             else
             {
                 NSLog(@"%@",error);
             }
             
         }];
    }
    else if (btn == self.weiboBtn)
    {
        [ShareSDK getUserInfo:SSDKPlatformTypeSinaWeibo
               onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
         {
             if (state == SSDKResponseStateSuccess)
             {
                 
//                 NSLog(@"用户标识:uid=%@",user.uid);
//                 NSLog(@"授权凭证: %@",user.credential);
//                 NSLog(@"token=%@",user.credential.token);
//                 NSLog(@"nickname=%@",user.nickname);
//                 NSLog(@"icon = %@",user.icon);
                 
                  [self showWithStatus:@"正在登录"];
                  NSDictionary *dict = @{@"type":@(2),@"name":user.nickname,@"image":user.icon,@"openId":user.uid,@"accessToken":user.credential.token,@"equipmentId":uniqueStr};
                 
                 WPLog(@"%@",dict);
                 
                 [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {
                     
                 } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                     
                     [self dismiss];
                     if ([responseObject[@"result"] isEqualToString:@"success"])
                     {
                         //            保存用户信息
                         WPUserAccount *userAccount = [WPUserAccount yy_modelWithDictionary:responseObject[@"detail"]];
                         [userAccount saveUserAccount];
                         
                         //设置请求头
                         NSString *tokenStr = [userAccount.token yy_modelToJSONString];
                         [[WPNetWorkManager sharedNetWorkManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];
                         
                         //用于绑定Alias的  使用NSString 即可
                         [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",userAccount.user.id] callbackSelector:nil object:self];
                         
                         //        登录成功
                         [self showSuccessInfoWithStatus:@"登陆成功"];
                         [self.navigationController dismissViewControllerAnimated:YES completion:nil];
                         
                         //友盟微博账号统计
                         [MobClick profileSignInWithPUID:userAccount.user.account provider:@"WB"];
                     }
                     else
                     {
                         [self showErrorInfoWithStatus:responseObject[@"detail"]];
                     }
                     
                 } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                     
                     [self dismiss];
                     [self showErrorInfoWithStatus:@"网络错误"];
                 }];

             }
             
             else
             {
                 NSLog(@"%@",error);
             }
             
         }];

    }
    else
    {
        [ShareSDK getUserInfo:SSDKPlatformTypeQQ
               onStateChanged:^(SSDKResponseState state, SSDKUser *user, NSError *error)
         {
             if (state == SSDKResponseStateSuccess)
             {
//                 NSLog(@"用户标识:uid=%@",user.uid);
//                 NSLog(@"授权凭证: %@",user.credential);
//                 NSLog(@"token=%@",user.credential.token);
//                 NSLog(@"nickname=%@",user.nickname);
//                 NSLog(@"icon = %@",user.icon);
                 
                 [self showWithStatus:@"正在登录"];
                 
                 //1.确定请求路径
                 NSString *urlStr = [NSString stringWithFormat:@"https://graph.qq.com/oauth2.0/me?access_token=%@&unionid=1",user.credential.token];
                 NSURL *url= [NSURL URLWithString:urlStr];
                 //2.创建请求对象
                 NSURLRequest *request = [NSURLRequest requestWithURL:url];
                 //3.创建会话管理者
                 AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
                 manager.responseSerializer  = [AFHTTPResponseSerializer serializer];
                 //是否接受无效的证书
                 manager.securityPolicy.allowInvalidCertificates= YES;
                 //是否匹配域名
                 manager.securityPolicy.validatesDomainName = NO;
                 NSURLSessionDataTask *dataTask = [manager dataTaskWithRequest:request completionHandler:^(NSURLResponse * _Nonnull response, id  _Nullable responseObject, NSError * _Nullable error) {
                     
                     if (error)
                     {
                         [self dismiss];
                         [self showErrorInfoWithStatus:@"登录失败"];
                     }
                     else
                     {
                         NSString *result = [[NSString alloc]initWithData:responseObject encoding:NSUTF8StringEncoding];
                         NSString *subStr = [NSString stringWithFormat:@"{%@}",[result subStringFrom:@"{" to:@"}"]];
                         
                         NSDictionary *dict = [self dictionaryWithJsonString:subStr];
                         
                         /*
                          {
                          "client_id" = 1105657762;
                          openid = 14262CE3A65902BD7F441C13D3EAE408;
                          unionid = "UID_425C3462E74686963FD0A504287193BD";
                          }
                          */
                         
                         NSDictionary *paraDict = @{@"type":@(0),@"name":user.nickname,@"image":user.icon,@"openId":dict[@"unionid"],@"accessToken":user.credential.token,@"equipmentId":uniqueStr};
                         //qq第三方登录
                         [self QQLoginWith:paraDict];
                     }
                     
                 }];
                 //4.执行任务
                 [dataTask resume];

             }
             
             else
             {
                 NSLog(@"%@",error);
             }
             
         }];
    }
}

-(void)QQLoginWith:(NSDictionary *)dict
{
    
    NSString *url = @"user/thirdPartyLogin.do";
    
     [[WPNetWorkManager sharedNetWorkManager] POST:url parameters:dict progress:^(NSProgress * _Nonnull uploadProgress) {

     } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {

         [self dismiss];
         if ([responseObject[@"result"] isEqualToString:@"success"])
         {
             //            保存用户信息
             WPUserAccount *userAccount = [WPUserAccount yy_modelWithDictionary:responseObject[@"detail"]];
             [userAccount saveUserAccount];

             //设置请求头
             NSString *tokenStr = [userAccount.token yy_modelToJSONString];
             [[WPNetWorkManager sharedNetWorkManager].requestSerializer setValue:tokenStr forHTTPHeaderField:@"token"];

             //用于绑定Alias的  使用NSString 即可
             [JPUSHService setAlias:[NSString stringWithFormat:@"%zd",userAccount.user.id] callbackSelector:nil object:self];

             //        登录成功
             [self showSuccessInfoWithStatus:@"登陆成功"];
             [self.navigationController dismissViewControllerAnimated:YES completion:nil];

             //友盟QQ账号统计
             [MobClick profileSignInWithPUID:userAccount.user.account provider:@"QQ"];
         }
         else
         {
             [self showErrorInfoWithStatus:responseObject[@"detail"]];
         }

     } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
         [self dismiss];
         [self showErrorInfoWithStatus:@"网络错误"];
     }];
}

-(NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData options: NSJSONReadingMutableContainers error:&err];
    if(err)
    {
        WPLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

#pragma mark - UITextField代理
-(BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self loginBtnDidClick];
    return YES;
}

@end













